class ChatNotes {
    constructor() {
        this.notes = [];
        this.currentEditingId = null;
        this.contextMenuTarget = null;

        this.initElements();
        this.bindEvents();
        this.loadNotes();
    }

    initElements() {
        this.messagesContainer = document.getElementById('messagesContainer');
        this.noteInput = document.getElementById('noteInput');
        this.sendBtn = document.getElementById('sendBtn');
        this.clearBtn = document.getElementById('clearBtn');
        this.addPageBtn = document.getElementById('addPageBtn');
        this.screenshotBtn = document.getElementById('screenshotBtn');
        this.noteCount = document.querySelector('.note-count');
        this.charCount = document.getElementById('charCount');
        this.contextMenu = document.getElementById('contextMenu');
    }

    bindEvents() {
        // 发送按钮点击事件
        this.sendBtn.addEventListener('click', () => this.handleSend());

        // 输入框事件
        this.noteInput.addEventListener('input', () => this.handleInput());
        this.noteInput.addEventListener('keydown', (e) => this.handleKeydown(e));

        // 清空按钮事件
        this.clearBtn.addEventListener('click', () => this.handleClear());

        // 添加网页信息按钮事件
        this.addPageBtn.addEventListener('click', () => this.handleAddPageInfo());

        // 截图按钮事件
        this.screenshotBtn.addEventListener('click', () => this.handleScreenshot());

        // 右键菜单事件
        document.addEventListener('contextmenu', (e) => this.handleContextMenu(e));
        document.addEventListener('click', () => this.hideContextMenu());

        // 右键菜单项事件
        document.getElementById('editNote').addEventListener('click', () => this.editNote());
        document.getElementById('deleteNote').addEventListener('click', () => this.deleteNote());
        document.getElementById('copyNote').addEventListener('click', () => this.copyNote());
    }

    handleInput() {
        const text = this.noteInput.value;
        const length = text.length;

        // 更新字符计数
        this.charCount.textContent = `${length}/1000`;
        this.charCount.style.color = length > 900 ? '#ff4d4f' : '#999';

        // 自动调整高度
        this.noteInput.style.height = 'auto';
        this.noteInput.style.height = Math.min(this.noteInput.scrollHeight, 100) + 'px';

        // 更新发送按钮状态
        this.sendBtn.disabled = text.trim().length === 0;
    }

    handleKeydown(e) {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            this.handleSend();
        }
    }

    handleSend() {
        const text = this.noteInput.value.trim();
        if (text.length === 0) return;

        if (this.currentEditingId) {
            // 更新现有笔记
            this.updateNote(this.currentEditingId, text);
            this.currentEditingId = null;
        } else {
            // 添加新笔记
            this.addNote(text);
        }

        this.noteInput.value = '';
        this.noteInput.style.height = 'auto';
        this.handleInput();
        this.noteInput.focus();
    }

    addNote(text) {
        const note = {
            id: Date.now().toString(),
            content: text,
            timestamp: new Date(),
            edited: false
        };

        this.notes.push(note);
        this.renderNote(note);
        this.saveNotes();
        this.updateNoteCount();
        this.scrollToBottom();
    }

    updateNote(id, newContent) {
        const noteIndex = this.notes.findIndex(note => note.id === id);
        if (noteIndex === -1) return;

        this.notes[noteIndex].content = newContent;
        this.notes[noteIndex].edited = true;
        this.notes[noteIndex].editedAt = new Date();

        // 更新 DOM 中的笔记
        const messageBubble = document.querySelector(`[data-note-id="${id}"] .message-bubble`);
        if (messageBubble) {
            messageBubble.textContent = newContent;
            messageBubble.classList.remove('editing');
        }

        this.saveNotes();
    }

    renderNote(note) {
        const messageDiv = document.createElement('div');
        messageDiv.className = 'message';
        messageDiv.setAttribute('data-note-id', note.id);

        const bubbleDiv = document.createElement('div');
        bubbleDiv.className = 'message-bubble';
        bubbleDiv.textContent = note.content;

        const timeDiv = document.createElement('div');
        timeDiv.className = 'message-time';
        timeDiv.textContent = this.formatTime(note.timestamp);
        if (note.edited) {
            timeDiv.textContent += ' (已编辑)';
        }

        messageDiv.appendChild(bubbleDiv);
        messageDiv.appendChild(timeDiv);

        // 如果是第一条笔记，移除欢迎消息
        if (this.notes.length === 1) {
            const welcomeMessage = this.messagesContainer.querySelector('.welcome-message');
            if (welcomeMessage) {
                welcomeMessage.remove();
            }
        }

        this.messagesContainer.appendChild(messageDiv);
    }

    renderNoteWithScreenshot(note) {
        const messageDiv = document.createElement('div');
        messageDiv.className = 'message';
        messageDiv.setAttribute('data-note-id', note.id);

        const bubbleDiv = document.createElement('div');
        bubbleDiv.className = 'message-bubble screenshot-bubble';

        // 添加文本内容
        const textDiv = document.createElement('div');
        textDiv.className = 'screenshot-text';
        textDiv.textContent = note.content;
        bubbleDiv.appendChild(textDiv);

        // 添加截图
        if (note.screenshot) {
            const imgDiv = document.createElement('div');
            imgDiv.className = 'screenshot-container';

            const img = document.createElement('img');
            img.src = note.screenshot;
            img.className = 'screenshot-image';
            img.alt = '网页截图';

            // 添加点击放大功能
            img.addEventListener('click', () => this.showFullScreenshot(note.screenshot));

            imgDiv.appendChild(img);
            bubbleDiv.appendChild(imgDiv);
        }

        const timeDiv = document.createElement('div');
        timeDiv.className = 'message-time';
        timeDiv.textContent = this.formatTime(note.timestamp);
        if (note.edited) {
            timeDiv.textContent += ' (已编辑)';
        }

        messageDiv.appendChild(bubbleDiv);
        messageDiv.appendChild(timeDiv);

        // 如果是第一条笔记，移除欢迎消息
        if (this.notes.length === 1) {
            const welcomeMessage = this.messagesContainer.querySelector('.welcome-message');
            if (welcomeMessage) {
                welcomeMessage.remove();
            }
        }

        this.messagesContainer.appendChild(messageDiv);
    }

    deleteNote(id) {
        if (!id && this.contextMenuTarget) {
            id = this.contextMenuTarget.getAttribute('data-note-id');
        }
        if (!id) return;

        if (confirm('确定要删除这条笔记吗？')) {
            // 从数组中移除
            this.notes = this.notes.filter(note => note.id !== id);

            // 从 DOM 中移除
            const messageElement = document.querySelector(`[data-note-id="${id}"]`);
            if (messageElement) {
                messageElement.remove();
            }

            this.saveNotes();
            this.updateNoteCount();

            // 如果没有笔记了，显示欢迎消息
            if (this.notes.length === 0) {
                this.showWelcomeMessage();
            }
        }
    }

    editNote(id) {
        if (!id && this.contextMenuTarget) {
            id = this.contextMenuTarget.getAttribute('data-note-id');
        }
        if (!id) return;

        const note = this.notes.find(n => n.id === id);
        if (!note) return;

        // 设置输入框内容
        this.noteInput.value = note.content;
        this.currentEditingId = id;

        // 标记正在编辑的消息
        const messageBubble = document.querySelector(`[data-note-id="${id}"] .message-bubble`);
        if (messageBubble) {
            messageBubble.classList.add('editing');
        }

        this.handleInput();
        this.noteInput.focus();
        this.noteInput.setSelectionRange(note.content.length, note.content.length);
    }

    copyNote(id) {
        if (!id && this.contextMenuTarget) {
            id = this.contextMenuTarget.getAttribute('data-note-id');
        }
        if (!id) return;

        const note = this.notes.find(n => n.id === id);
        if (!note) return;

        navigator.clipboard.writeText(note.content).then(() => {
            // 显示复制成功提示
            this.showToast('已复制到剪贴板');
        }).catch(() => {
            // 降级方案
            const textArea = document.createElement('textarea');
            textArea.value = note.content;
            document.body.appendChild(textArea);
            textArea.select();
            document.execCommand('copy');
            document.body.removeChild(textArea);
            this.showToast('已复制到剪贴板');
        });
    }

    async handleAddPageInfo() {
        try {
            // 获取当前活动标签页信息
            const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });

            if (!tab) {
                this.showToast('无法获取当前网页信息');
                return;
            }

            // 构建网页信息文本
            let pageInfo = `🌐 ${tab.title}\n🔗 ${tab.url}`;

            // 如果输入框已有内容，添加换行
            const currentText = this.noteInput.value.trim();
            if (currentText) {
                this.noteInput.value = currentText + '\n\n' + pageInfo;
            } else {
                this.noteInput.value = pageInfo;
            }

            // 更新输入框状态
            this.handleInput();
            this.noteInput.focus();

        } catch (error) {
            console.error('获取网页信息失败：', error);
            this.showToast('获取网页信息失败');
        }
    }

    async handleScreenshot() {
        try {
            // 显示加载提示
            this.showToast('正在截取网页...');

            // 获取当前活动标签页
            const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });

            if (!tab) {
                this.showToast('无法获取当前标签页');
                return;
            }

            // 截取当前标签页
            const screenshotUrl = await chrome.tabs.captureVisibleTab(tab.windowId, {
                format: 'png',
                quality: 100
            });

            // 创建包含截图的笔记
            const note = {
                id: Date.now().toString(),
                content: `📸 网页截图\n🌐 ${tab.title}\n🔗 ${tab.url}`,
                timestamp: new Date(),
                edited: false,
                screenshot: screenshotUrl
            };

            this.notes.push(note);
            this.renderNoteWithScreenshot(note);
            this.saveNotes();
            this.updateNoteCount();
            this.scrollToBottom();

            this.showToast('截图已保存');

        } catch (error) {
            console.error('截图失败：', error);
            this.showToast('截图失败，请检查权限设置');
        }
    }

    handleClear() {
        if (this.notes.length === 0) return;

        if (confirm(`确定要清空所有 ${this.notes.length} 条笔记吗？此操作不可恢复。`)) {
            this.notes = [];
            this.messagesContainer.innerHTML = '';
            this.showWelcomeMessage();
            this.saveNotes();
            this.updateNoteCount();
        }
    }

    handleContextMenu(e) {
        const messageBubble = e.target.closest('.message-bubble');
        if (!messageBubble) {
            this.hideContextMenu();
            return;
        }

        e.preventDefault();
        this.contextMenuTarget = messageBubble.closest('.message');

        // 显示右键菜单
        this.contextMenu.style.display = 'block';
        this.contextMenu.style.left = e.pageX + 'px';
        this.contextMenu.style.top = e.pageY + 'px';

        // 确保菜单不超出视窗
        const rect = this.contextMenu.getBoundingClientRect();
        const windowWidth = window.innerWidth;
        const windowHeight = window.innerHeight;

        if (rect.right > windowWidth) {
            this.contextMenu.style.left = (e.pageX - rect.width) + 'px';
        }
        if (rect.bottom > windowHeight) {
            this.contextMenu.style.top = (e.pageY - rect.height) + 'px';
        }
    }

    hideContextMenu() {
        this.contextMenu.style.display = 'none';
        this.contextMenuTarget = null;
    }

    showWelcomeMessage() {
        const welcomeDiv = document.createElement('div');
        welcomeDiv.className = 'welcome-message';
        welcomeDiv.innerHTML = `
            <div class="system-message">
                <span>🎉 欢迎使用聊天式笔记本！</span>
                <p>你可以像聊天一样记录你的想法和笔记</p>
            </div>
        `;
        this.messagesContainer.appendChild(welcomeDiv);
    }

    updateNoteCount() {
        this.noteCount.textContent = `${this.notes.length} 条笔记`;
    }

    formatTime(date) {
        // 确保 date 是 Date 对象
        const dateObj = date instanceof Date ? date : new Date(date);

        // 检查日期是否有效
        if (isNaN(dateObj.getTime())) {
            return '无效日期';
        }

        const now = new Date();
        const diff = now - dateObj;
        const minutes = Math.floor(diff / 60000);
        const hours = Math.floor(diff / 3600000);
        const days = Math.floor(diff / 86400000);

        if (minutes < 1) return '刚刚';
        if (minutes < 60) return `${minutes}分钟前`;
        if (hours < 24) return `${hours}小时前`;
        if (days < 7) return `${days}天前`;

        return dateObj.toLocaleDateString('zh-CN', {
            month: 'short',
            day: 'numeric',
            hour: '2-digit',
            minute: '2-digit'
        });
    }

    scrollToBottom() {
        setTimeout(() => {
            this.messagesContainer.scrollTop = this.messagesContainer.scrollHeight;
        }, 100);
    }

    showToast(message) {
        // 简单的提示消息
        const toast = document.createElement('div');
        toast.style.cssText = `
            position: fixed;
            top: 20px;
            left: 50%;
            transform: translateX(-50%);
            background: #323232;
            color: white;
            padding: 8px 16px;
            border-radius: 4px;
            font-size: 14px;
            z-index: 10000;
            animation: slideDown 0.3s ease-out;
        `;
        toast.textContent = message;

        document.body.appendChild(toast);

        setTimeout(() => {
            toast.style.animation = 'slideUp 0.3s ease-out forwards';
            setTimeout(() => toast.remove(), 300);
        }, 2000);
    }

    showFullScreenshot(screenshotUrl) {
        // 创建全屏遮罩层
        const overlay = document.createElement('div');
        overlay.style.cssText = `
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.9);
            z-index: 10001;
            display: flex;
            justify-content: center;
            align-items: center;
            cursor: pointer;
        `;

        // 创建大图
        const img = document.createElement('img');
        img.src = screenshotUrl;
        img.style.cssText = `
            max-width: 90%;
            max-height: 90%;
            border-radius: 8px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.5);
        `;

        overlay.appendChild(img);
        document.body.appendChild(overlay);

        // 点击关闭
        overlay.addEventListener('click', () => {
            overlay.remove();
        });

        // ESC 键关闭
        const handleKeydown = (e) => {
            if (e.key === 'Escape') {
                overlay.remove();
                document.removeEventListener('keydown', handleKeydown);
            }
        };
        document.addEventListener('keydown', handleKeydown);
    }

    saveNotes() {
        chrome.storage.local.set({ chatNotes: this.notes }, () => {
            if (chrome.runtime.lastError) {
                console.error('保存笔记失败：', chrome.runtime.lastError);
            }
        });
    }

    loadNotes() {
        chrome.storage.local.get('chatNotes', (result) => {
            if (chrome.runtime.lastError) {
                console.error('加载笔记失败：', chrome.runtime.lastError);
                return;
            }

            this.notes = result.chatNotes || [];

            if (this.notes.length === 0) {
                this.showWelcomeMessage();
            } else {
                // 移除欢迎消息
                const welcomeMessage = this.messagesContainer.querySelector('.welcome-message');
                if (welcomeMessage) {
                    welcomeMessage.remove();
                }

                // 渲染所有笔记
                this.notes.forEach(note => {
                    // 确保 timestamp 是 Date 对象
                    if (typeof note.timestamp === 'string') {
                        note.timestamp = new Date(note.timestamp);
                    }
                    // 确保 editedAt 也是 Date 对象（如果存在）
                    if (note.editedAt && typeof note.editedAt === 'string') {
                        note.editedAt = new Date(note.editedAt);
                    }

                    // 根据是否有截图选择渲染方法
                    if (note.screenshot) {
                        this.renderNoteWithScreenshot(note);
                    } else {
                        this.renderNote(note);
                    }
                });

                this.scrollToBottom();
            }

            this.updateNoteCount();
        });
    }
}

// 添加 CSS 动画
const style = document.createElement('style');
style.textContent = `
    @keyframes slideDown {
        from { transform: translateX(-50%) translateY(-20px); opacity: 0; }
        to { transform: translateX(-50%) translateY(0); opacity: 1; }
    }
    @keyframes slideUp {
        from { transform: translateX(-50%) translateY(0); opacity: 1; }
        to { transform: translateX(-50%) translateY(-20px); opacity: 0; }
    }
`;
document.head.appendChild(style);

// 初始化应用
document.addEventListener('DOMContentLoaded', () => {
    new ChatNotes();
});